package com.lgl.service.impl;

import com.lgl.dao.IAuthTokenDao;
import com.lgl.dao.IUserDao;
import com.lgl.pojo.AuthCode;
import com.lgl.pojo.AuthToken;
import com.lgl.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private IUserDao userDao;

    @Autowired
    private IAuthTokenDao authTokenDao;

    @Override
    public boolean register(String email, String password, String code) {

        //注册维护验证码
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreatetime(new Date());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 10);
        authCode.setExpiretime(calendar.getTime());
        AuthCode save = userDao.save(authCode);

        //注册维护token
        String token = email + password;
        AuthToken authToken = new AuthToken();
        authToken.setEmail(email);
        authToken.setToken(token);
        AuthToken saveToken = authTokenDao.save(authToken);

        return save != null;
    }

    /**
     * 是否已经注册
     * @param email 邮件
     * @return
     */
    @Override
    public boolean isRegistered(String email) {
        List<AuthCode> list = userDao.findByEmail(email);
        return list != null && list.size() != 0;
    }

    @Override
    public boolean login(String email, String password) {
        if (!isRegistered(email)) {
            return false;
        }
        String validEmail = findEmailByToken(email + password);
        return validEmail != "";
    }


    @Override
    public String findEmailByToken(String token) {
        List<AuthToken> byToken = authTokenDao.findByToken(token);
        if (byToken != null && byToken.size() > 0) {
            AuthToken authToken = byToken.get(0);
            return authToken.getEmail();
        }

        return "";
    }
}
